import axios from 'axios'
import { globalUrl, normalHeaders, formHeaders, verifyHeaders } from './global'
import { User } from '@/models/loginReg'

async function toLogin(account: string, password: string){
    const config = {
        headers: formHeaders
    };
    const formdata = new FormData();
    formdata.append("username", account);
    formdata.append("password", password);
    try{
        const res = await axios.post(globalUrl + "sql/token", formdata, config);
        if(res.status == 200 && res.data.code == 0){
            localStorage.Authorization = 'Bearer ' + res.data.access_token;
            return 0;
        } else {
            return 1;
        }
    } catch(error){
        console.log(error);
        return 2;
    }
}

async function toRegister(name: string, account: string, password: string, sex: number): Promise<boolean>{
    const config = {
        headers: normalHeaders
    };
    let flag = false;
    const data = {
        name: name,
        number: account,
        password: password,
        sex: sex
    }

    await axios.post(globalUrl + "sql/users/create", data, config)
    .then(res => {
        console.log(res.status);
        if (res.status == 200 && res.data.code == 0){
            flag = true;
        }
    });
    return flag;
}

async function updateUser(account: string, name?: string, sex?: number){
    const config = {
        headers: verifyHeaders
    };
    const data = {
        account: account,
        name: name,
        sex: sex,
    }
    try{
        const userRes = await axios.post(globalUrl + 'sql/users/update', data, config);
        if (userRes.status == 200){
            return 0;
        } else {
            return 1;
        }
        
    } catch(error) {
        console.log(error);
        return 2;
    }
}

async function getSelf(): Promise<User | null>{
    const config = {
        headers: verifyHeaders
    };
    let user !: User;
    config.headers.Authorization = localStorage.Authorization;
    const res = await axios.get(globalUrl + 'sql/users/get/self', config);
    const classes: string[] = [];
    if (res.status == 200 && res.data.code == 0){
        user = res.data.user;
        res.data.classes.forEach(element => {
            console.log(element.name);
            classes.push(element.name);
        });
        user.classes = classes;
    }
    console.log(res);
    return user
}

async function linkClass(account: string, className: string[]) {
    for (let i = 0; i < className.length; i++){
        const data = {
            number: account,
            class_name: className[i]
        }
        try {
            const res =await axios.post(globalUrl + 'sql/classes/link_user', data, {headers: verifyHeaders});
            if (res.status == 200) {
                return 0;
            }
        } catch(error){
            console.log(error);
            return 2;
        }
    }
}

export { toLogin, getSelf, toRegister, updateUser, linkClass };
